package net.hn.hnms.biz.safety.trinity.company.service;

import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.safety.trinity.model.DangerInfoVo;
import net.hn.hnms.biz.api.safety.trinity.model.HiddenDangerCheckVo;
import net.hn.hnms.biz.api.safety.trinity.model.HiddenDangerCountVO;
import net.hn.hnms.biz.safety.trinity.dao.HiddenDangerAcceptDao;
import net.hn.hnms.biz.safety.trinity.dao.HiddenDangerListDao;
import net.hn.hnms.biz.safety.trinity.dao.HiddenDangerReformDao;
import net.hn.hnms.biz.safety.trinity.entity.*;
import net.hn.hnms.biz.safety.trinity.until.MineName;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 智呈物联 nzw
 * @date 2023/1/5
 */

@Service
@RequiredArgsConstructor
public class HiddanGroupDangerRecordCompanyService {

    private final JdbcTemplate locationJdbcTemplate;

    HiddenDangerListDao hiddenDangerListDao;

    HiddenDangerAcceptDao hiddenDangerAcceptDao;

    HiddenDangerReformDao hiddenDangerReformDao;

    MineName mineName;

    @Autowired
    public void setHiddenDangerListDao(HiddenDangerListDao hiddenDangerListDao) {
        this.hiddenDangerListDao = hiddenDangerListDao;
    }

    @Autowired
    public void setHiddenDangerAcceptDao(HiddenDangerAcceptDao hiddenDangerAcceptDao) {
        this.hiddenDangerAcceptDao = hiddenDangerAcceptDao;
    }

    @Autowired
    public void setHiddenDangerReformDao(HiddenDangerReformDao hiddenDangerReformDao) {
        this.hiddenDangerReformDao = hiddenDangerReformDao;
    }

    @Autowired
    public void setMineName(MineName mineName) {
        this.mineName = mineName;
    }

    /**
     * 获取本年第一天日期
     * @return 返回第一天日期
     */
    private String getDate(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-01-01");
        Calendar calendar = Calendar.getInstance();
        return simpleDateFormat.format(calendar.getTime());
    }

    /**
     * 参数处理，为传入时间参数添加默认值
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 处理后结果
     */
    private Map<String,String> processingTime(String startTime,String endTime){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if((startTime==null||"".equals(startTime))&&(endTime==null||"".equals(endTime))){
            startTime = getDate();
            endTime = simpleDateFormat.format(new Date());
        }else if (startTime==null||"".equals(startTime)){
            startTime = "2000-01-01";
        }else if (endTime==null||"".equals(endTime)){
            endTime = simpleDateFormat.format(new Date());
        }
        Map<String,String> map = new HashMap<>();
        map.put("startTime",startTime);
        map.put("endTime",endTime);
        return map;
    }

    /**
     * 隐患等级处理
     * @param list 隐患数据
     * @return 前端隐患对象
     */
    private HiddenDangerLevelVO level(List<Map<String,Object>> list){
        HiddenDangerLevelVO hiddenDangerLevelVO = new HiddenDangerLevelVO();
        for (Map<String,Object> map : list){
            String level = map.get("danger_level")+"";
            switch (level){
                case "2":
                    hiddenDangerLevelVO.setAHiddenDanger(map.get("count")+"");
                    break;
                case "3":
                    hiddenDangerLevelVO.setBHiddenDanger(map.get("count")+"");
                    break;
                case "4":
                    hiddenDangerLevelVO.setGenerallyHiddenDanger(map.get("count")+"");
                    break;
                case "1":
                    hiddenDangerLevelVO.setMajorHiddenDanger(map.get("count")+"");
                    break;
            }

        }
        return hiddenDangerLevelVO;
    }

    /**
     * 公司/集团端隐患台账分页封装
     * @param list sql查询结果
     * @return 分页对象
     */
    private ResponsePage<HiddenDangerCompanyVO> page(List<Map<String,Object>> list,String count){
        List<HiddenDangerCompanyVO> hiddenDangerCompanyVOS = new LinkedList<>();
        for (Map<String,Object> map:list){
            HiddenDangerCompanyVO hiddenDangerCompanyVO = new HiddenDangerCompanyVO();
            hiddenDangerCompanyVO.setCompanyName(mineName.getParentMineName(map.get("mine_code")+""));
            hiddenDangerCompanyVO.setMineCode(map.get("mine_code")+"");
            hiddenDangerCompanyVO.setMineName(mineName.getMineName(map.get("mine_code")+""));
            hiddenDangerCompanyVO.setDataTime(map.get("check_date")+"");
            String hiddenDangerLevel = map.get("danger_level")+"";
            switch(hiddenDangerLevel){
                case "2":
                    hiddenDangerLevel = "一般隐患(A)";
                    break;
                case "3":
                    hiddenDangerLevel = "一般隐患(B)";
                    break;
                case "4":
                    hiddenDangerLevel = "一般隐患(C)";
                    break;
                default:
                    hiddenDangerLevel = "重大隐患";
                    break;
            }
            hiddenDangerCompanyVO.setHiddenDangerLevel(hiddenDangerLevel);
            hiddenDangerCompanyVO.setHiddenDangerState(getDangerStateName(map.get("danger_status")+""));
            hiddenDangerCompanyVOS.add(hiddenDangerCompanyVO);
        }
        ResponsePage<HiddenDangerCompanyVO> responsePage = new ResponsePage<HiddenDangerCompanyVO>(hiddenDangerCompanyVOS,Integer.parseInt(count));
        return responsePage;
    }

    public String getDangerStateName(String dangerStatus){
        switch (dangerStatus){
            case "0":
                return "未整改";
            case "1":
                return "已整改";
            case "3":
                return "整改中";
        }
        return "";
    }

    /**
     * 公司集团端隐患台账
     * @param pageQuery 分页
     * @param state 状态
     * @param level 等级
     * @param mineCode 煤矿编码
     * @param overdueTime 逾期时间
     * @param dataTime 数据时间
     * @param startTime 时间段-开始时间
     * @param endTime 时间段-结束时间
     * @return
     */
    public ResponsePage<HiddenDangerCompanyVO> hiddenDangerStatePage(PageQuery pageQuery, String state,String level,String mineCode,String overdueTime,String dataTime, String startTime, String endTime){
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");
        String sql = "SELECT\n" +
                "\t*\n" +
                "FROM\n" +
                "\thidden_danger_list \n";
        String count = "SELECT\n" +
                "\tcount(*)\n" +
                "FROM\n" +
                "\thidden_danger_list \n";
        String where = " WHERE 1=1 ";
        //条件
        //时间
        if(startTime!=null&&!"".equals(startTime)){
            where += " AND to_char( check_date, 'yyyy-MM-dd' ) >='" +startTime+"' ";
        }
        if (endTime!=null&&!"".equals(endTime)){
            where += " AND to_char( check_date, 'yyyy-MM-dd' ) <=  '" +endTime+"' ";
        }

        //状态
        if(state!=null&&!"".equals(state)) {
            switch (state) {
                case "1":
                    where += "AND ( danger_status = '1' AND approve_status = '1' ) ";
                    break;
                case "0":
                    where += "AND ( danger_status = '0' AND approve_status = '1' ) ";
                    break;
                case "3":
                    where += "AND ( danger_status = '3' AND approve_status = '2' )";
                    break;
            }
        }else {
            where += "\tAND (( danger_status = '1' AND approve_status = '1' ) \n" +
                    "\tOR ( danger_status = '0' AND approve_status = '1' ) \n" +
                    "\tOR ( danger_status = '3' AND approve_status = '2' ))  " ;
        }
        //隐患等级
        if(level!=null&&!"".equals(level)){
            where += " AND danger_level = '"+level+"'";
        }

        if (mineCode!=null&&!"".equals(mineCode)){
            where += " AND mine_code = '"+mineCode+"'";
        }

        if (dataTime!=null&&!"".equals(dataTime)){
            where += " AND to_char( check_date, 'yyyy-MM-dd' ) = '"+dataTime+"'";
        }

        if (overdueTime!=null&&!"".equals(dataTime)){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (overdueTime.equals("8")){
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                where += "AND to_char( reform_deadline, 'yyyy-MM-dd' ) < '" + simpleDateFormat.format(calendar.getTime()) + "'";
            }else {
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - Integer.parseInt(overdueTime+""));
                where += "AND to_char( reform_deadline, 'yyyy-MM-dd' ) = '" + simpleDateFormat.format(calendar.getTime()) + "'";
            }
        }

        //分页条件
        Integer pageSize = pageQuery.getPageSize();
        if (pageSize==null){
            pageSize = 10;
        }
        Integer pageNum = pageQuery.getPageNum();
        if (pageNum==null||pageNum==0){
            pageNum=1;
        }
        String page = " order by check_date desc LIMIT "+pageSize+" OFFSET "+(pageNum-1)*pageSize;

        List<Map<String,Object>> list = locationJdbcTemplate.queryForList(sql+where+page);
        Map<String,Object> map = locationJdbcTemplate.queryForMap(count+where);
        return page(list,map.get("count")+"");
    }


    public HiddenDangerCheckVo hiddenDangerCheck(){

        String time = getDate();
        HiddenDangerCheckVo hiddenDangerCheckVo = new HiddenDangerCheckVo();
        //隐患总数
        int dangerCount = hiddenDangerListDao.countAll();
        hiddenDangerCheckVo.setDangerCount(dangerCount);
        //重大隐患
        hiddenDangerCheckVo.setMajor(hiddenDangerListDao.countAllLevel());

        //待整改隐患
        int rectified = hiddenDangerListDao.rectified();
        hiddenDangerCheckVo.setRectified(rectified);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp timestamp = Timestamp.valueOf(simpleDateFormat.format(new Date()));

        //所有超过期限的隐患
        int dealine = hiddenDangerListDao.countAllDeadline(time);
        hiddenDangerCheckVo.setOverdue(dealine);

        return hiddenDangerCheckVo;
    }

    public DangerInfoVo hiddenDanger(){
        DangerInfoVo dangerInfoVo = new DangerInfoVo();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dataTime = simpleDateFormat.format(new Date());

        //新增隐患
        int hiddenDangerCount = hiddenDangerListDao.findAllLikeDataTime(dataTime);
        dangerInfoVo.setAdded(hiddenDangerCount);
        //累计验收通过的隐患
        Integer hiddenDangerAccepts = hiddenDangerListDao.ClosedLoopCount();
        dangerInfoVo.setClosedLoopCount(hiddenDangerAccepts);
        //整改隐患
        Integer hiddenDangerReforms = hiddenDangerListDao.NotClosedLoopCount();
        dangerInfoVo.setNotClosedLoopCount(hiddenDangerReforms);

        return dangerInfoVo;
    }

    public HiddenDangerSumVO hiddenDangerSum(){
        HiddenDangerSumVO hiddenDangerSumVO = new HiddenDangerSumVO();

        String time = getDate();
        //隐患总数
        int dangerCount = hiddenDangerListDao.countAll();
        hiddenDangerSumVO.setSum(dangerCount+"");

        List<HiddenDangerVO> hiddenDangerVOS = new ArrayList<>();
        List<Map<String,Object>> list = hiddenDangerListDao.countAllByMineCode(time);
        for (Map<String,Object> map:list){
            HiddenDangerVO hiddenDangerVO = new HiddenDangerVO();
            hiddenDangerVO.setMineName(mineName.getMineName(map.get("mine_code")+""));
            hiddenDangerVO.setMineCode(map.get("mine_code")+"");
            hiddenDangerVO.setHiddenDangerNum(map.get("count")+"");
            hiddenDangerVOS.add(hiddenDangerVO);
        }
        hiddenDangerSumVO.setList(hiddenDangerVOS);

        return hiddenDangerSumVO;
    }

    public HiddenDangerStateVO hiddenDangerState(String startTime, String endTime){
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");
        HiddenDangerStateVO hiddenDangerStateVO = new HiddenDangerStateVO();
        List<Map<String,Object>> list = hiddenDangerListDao.hiddenDangerState(startTime,endTime);
        for (Map<String,Object> map : list){
            String state = map.get("danger_status")+"";
            switch (state){
//                case "待销号":
//                    hiddenDangerStateVO.setPinNumber(map.get("count")+"");
//                    break;
                case "3":
                    hiddenDangerStateVO.setRectification(map.get("count")+"");
                    break;
//                case "待复查":
//                    hiddenDangerStateVO.setImplement(map.get("count")+"");
//                    break;
                case "1":
                    hiddenDangerStateVO.setAcceptance(map.get("count")+"");
                    break;
                default:
                    hiddenDangerStateVO.setRegister(new BigDecimal(hiddenDangerStateVO.getRegister()).add(new BigDecimal(map.get("count")+""))+"");
                    break;
            }
        }
        return hiddenDangerStateVO;
    }

    public HiddenDangerLevelVO hiddenDangerLevel(String startTime, String endTime){
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");
        List<Map<String,Object>> list = hiddenDangerListDao.hiddenDangerLevel(startTime,endTime);
        return level(list);
    }

    public List<HiddenDangerCompanyLevelVO> hiddenDangerCompanyLevel(String startTime, String endTime){
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");
        List<HiddenDangerCompanyLevelVO> hiddenDangerCompanyLevelVOS = new ArrayList<>();
        List<String> list = hiddenDangerListDao.hiddenDangerMineCode(startTime,endTime);
        for (String mineCode:list) {
            HiddenDangerCompanyLevelVO hiddenDangerCompanyLevelVO = new HiddenDangerCompanyLevelVO();
            hiddenDangerCompanyLevelVO.setMineName(mineName.getMineName(mineCode));
            hiddenDangerCompanyLevelVO.setMineCode(mineCode);
            List<Map<String,Object>> hiddenDangerLevels = hiddenDangerListDao.hiddenDangerLevel(startTime,endTime,mineCode);
            hiddenDangerCompanyLevelVO.setHiddenDangerLevelVO(level(hiddenDangerLevels));
            hiddenDangerCompanyLevelVOS.add(hiddenDangerCompanyLevelVO);
        }
        return hiddenDangerCompanyLevelVOS;
    }

    public HiddenDangerDateVO hiddenDangerDataTime(String startTime, String endTime) throws ParseException {
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");

        HiddenDangerDateVO hiddenDangerDate = new HiddenDangerDateVO();
        List<Map<String,Object>> list = hiddenDangerListDao.hiddenDangerDataTime(startTime,endTime);
        Map<String,Integer> time = new HashMap<>();
        for (Map<String,Object> map:list){
            time.put(map.get("check_date")+"",Integer.parseInt(map.get("count")+""));
        }

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        calendar.setTime(simpleDateFormat.parse(startTime));
        List<String> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();
        for (int i=0;i<500;i++){
            if (i==0){
                calendar.set(Calendar.DATE,calendar.get(Calendar.DATE));
            }else {
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
            }

            String xDateString = simpleDateFormat.format(calendar.getTime());
            Integer count = time.get(xDateString);
            if (count==null||"".equals(count)){
                count=0;
            }

            yData.add(count);
            xData.add(xDateString);
            if (xDateString.equals(year.format(new Date())+"-12-31")){
                break;
            }
        }
        hiddenDangerDate.setXDate(xData);
        hiddenDangerDate.setYHiddenDanger(yData);
        return hiddenDangerDate;
    }

    public HiddenDangerDateVO hiddenDangerOverdueTime(String startTime, String endTime){
        Map<String,String> processingTime = processingTime(startTime,endTime);
        startTime = processingTime.get("startTime");
        endTime = processingTime.get("endTime");

        HiddenDangerDateVO hiddenDangerDate = new HiddenDangerDateVO();
        String selectAllSql = "SELECT\n" +
                "\tcount(*) \n" +
                "FROM\n" +
                "\thidden_danger_list ";

        String where = " where danger_status != '已闭合'";
        where += "AND to_char( check_date, 'yyyy-MM-dd' ) >= '"+startTime+"' \n" +
                "\tAND to_char( check_date, 'yyyy-MM-dd' ) <= '"+endTime+"' ";

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> xData = new ArrayList<>(10);
        List<Integer> yData = new ArrayList<>(10);
        for (int i=1;i<9;i++){
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
            String overdueTime = simpleDateFormat.format(calendar.getTime());
            String overdueTimeWhere = "";
            if (i!=8) {
                xData.add("逾期"+i+"天");
                overdueTimeWhere = "AND to_char( reform_deadline, 'yyyy-MM-dd' ) = '" + overdueTime + "'";
            }else {
                xData.add("逾期>7天");
                overdueTimeWhere = "AND to_char( reform_deadline, 'yyyy-MM-dd' ) < '" + overdueTime + "'";
            }
            Map<String,Object> map = locationJdbcTemplate.queryForMap(selectAllSql+where+overdueTimeWhere);
            yData.add(Integer.parseInt(map.get("count")+""));
        }

        hiddenDangerDate.setXDate(xData);
        hiddenDangerDate.setYHiddenDanger(yData);
        return hiddenDangerDate;
    }

    public HiddenDangerCountVO hiddenDangerCount() {

        HiddenDangerCountVO hiddenDangerCountVO = new HiddenDangerCountVO();
        hiddenDangerCountVO.setMajorCount(hiddenDangerListDao.majorDangerCount());
        hiddenDangerCountVO.setOverdueCount(hiddenDangerListDao.majorOverdueCount());
        // todo 挂牌督办目前取不到
        hiddenDangerCountVO.setRectifiedCount(0);
        return hiddenDangerCountVO;
    }

    public void getHiddenDangerLevelYear(RiskHiddenDangerLevelVO riskHiddenDangerLevelVO){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        List<Map<String,Object>> list = new ArrayList<>(4);
        list = hiddenDangerListDao.getHiddenDangerLevelYear(simpleDateFormat.format(new Date())+"-01-01");
        list.forEach(map -> {
            String dangerLevel = map.get("danger_level")+"";
            String count = map.get("count")+"";
            switch(dangerLevel){
                case "2":
                    riskHiddenDangerLevelVO.setAHiddenDanger(count);
                    break;
                case "3":
                    riskHiddenDangerLevelVO.setBHiddenDanger(count);
                    break;
                case "4":
                    riskHiddenDangerLevelVO.setGenerallyHiddenDanger(count);
                    break;
                default:
                    riskHiddenDangerLevelVO.setMajorHiddenDanger(count);
                    break;
            }
        });
    }

}
